package com.cxh.controller.car;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.cxh.base.BaseController;
import com.cxh.entity.CarCategory;
import com.cxh.entity.CarLoan;
import com.cxh.entity.SysUser;
import com.cxh.util.CommonUtility;
import com.cxh.util.DateUtility;
import com.cxh.util.json.JSONUtil;

import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.List;
import java.util.Map;


/**
 * 类说明：
 * @author  ChenXH
 * @date  2018-12-11 13:57:58
 */
@Controller
@RequestMapping(value = "/controller/carLoan")
public class CarLoanController extends BaseController {

    /**
     * 方法说明：进入页面
     * @author  ChenXH
     * @date  2018-12-11 13:57:58
     */
    @RequestMapping(value = "/list")
    public ModelAndView list (HttpServletRequest request, HttpServletResponse response){
        ModelAndView model =  new ModelAndView();
        model.setViewName("car/carLoan/carLoanlist");
        return model;
    }

    /**
     * 方法说明：获得表格数据
     * @author  ChenXH
     * @date  2018-12-11 13:57:58
     */
    @RequestMapping(value = "/showList")
    @ResponseBody
    public String showList (HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
    	//获取用户的信息
    	HttpSession session = request.getSession();
    	SysUser user = (SysUser)session.getAttribute("user");
    	//查询用户的角色
    	List<Integer> roleByUserId = sysUserRoleService.getRoleByUserId(user.getUserid());
    	if(roleByUserId.size()!=0){
    		//1默认是超级管理员，如果不包含就放入map中，只查询自己的信息
    		if(!roleByUserId.contains(1)){
    			params.put("userid", user.getUserid());
    		}
    	}
    	//
        String json="";
        //获得  页码数
        Integer page=CommonUtility.isEmpty(params.get("page"))?1:Integer.parseInt(params.get("page")+"");
        //获得 每页的行数
        Integer limit=CommonUtility.isEmpty(params.get("limit"))?10:Integer.parseInt(params.get("limit")+"");
        //设置 分页参数
        PageHelper.startPage(page,limit);
        //调用 查询方法
        List<CarLoan> carLoanList=carLoanService.loadPageList(params);
        //处理数据
        PageInfo<CarLoan> pageInfo=new PageInfo<CarLoan>(carLoanList);
        try {
            //转换 时间格式/并将数据转换成json字符串
            JsonConfig jsonConfig = JSONUtil.getJsonConfig(DateUtility.DateFormat1);
            json= JSONUtil.toLayUIJSONAll(pageInfo.getTotal(),pageInfo.getList(), jsonConfig);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 方法说明：进入编辑页面
     * @author  ChenXH
     * @date  2018-12-11 13:57:58
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit (HttpServletRequest request, HttpServletResponse response){
        //获得要修改数据的Id
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        ModelAndView model=new ModelAndView();
        CarLoan carLoan=new CarLoan();
        try {
        	 //查询雪佛兰汽车类型
            List<CarCategory> carCategoryList = carCategoryService.getXFLCategory();
            //判断是 修改  还是 新增
            if (!CommonUtility.isEmpty(entityId)&&entityId>0) {
                carLoan = carLoanService.selectByPrimaryKey(entityId);
                // 进行数据准备
                model.addObject("carLoan",carLoan);
            }
            StringBuilder sb = new StringBuilder();
            sb.append("<option value=\"\"></option>");
            for (CarCategory carCategory : carCategoryList) {
            	if(carCategory.getCarcategoryid().equals(carLoan.getCarcategoryid())){
            		sb.append("<option value=\""+carCategory.getCarcategoryid()+"\" selected>"+carCategory.getCarcategoryname()+"</option>");
            	}else{
            		sb.append("<option value=\""+carCategory.getCarcategoryid()+"\">"+carCategory.getCarcategoryname()+"</option>");
            	}
			}
            model.addObject("carCategoryList",sb.toString());
            //返回视图位置
            model.setViewName("car/carLoan/carLoanForm");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

    /**
     * 方法说明：保存/修改
     * @author  ChenXH
     * @date  2018-12-11 13:57:58
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public String save (HttpServletRequest request, HttpServletResponse response,@RequestParam  Map<String,Object> jsonMap){
    	HttpSession session = request.getSession();
    	SysUser user = (SysUser)session.getAttribute("user");
    	//根据用户id查询经销商
    	//CarAgency carAgency= carAgencyService.getAgencyByUserId(user.getUserid());
    	
        //执行状态（0成功；1失败）
        int flag=0;
        int entityId=CommonUtility.isEmpty(jsonMap.get("entityId"))?0:Integer.parseInt(jsonMap.get("entityId")+"");
        
        Object carcategoryid = jsonMap.get("carcategoryid");
        Object monthnum = jsonMap.get("monthnum");
        Object money = jsonMap.get("money");
        
        //进行 修改
        if(entityId>0){
            CarLoan carLoan=carLoanService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(carLoan)){
            	carLoan.setUserid(user.getUserid());
                carLoan.setCarcategoryid(carcategoryid+"");
                carLoan.setMonthnum(monthnum+"");
                carLoan.setMoney(money+"");
                try {
                    //修改
                    carLoanService.updateByPrimaryKey(carLoan);
                    //operationLog(request, "修改用户" + user.getLoginName(), TableConstants.LOG_TYPES_EDIT);
                }catch (Exception e) {
                    flag = 1;
                    e.printStackTrace();
                }
            }else{
                flag=1;
            }
        }else{
            //进行数据添加
            CarLoan carLoan=new CarLoan();
            carLoan.setUserid(user.getUserid());
            carLoan.setCarcategoryid(carcategoryid+"");
            carLoan.setMonthnum(monthnum+"");
            carLoan.setMoney(money+"");
            try {
                //新增
                carLoanService.insert(carLoan);
                //operationLog(request, "添加用户" + user.getLoginName(), TableConstants.LOG_TYPES_ADD);
            }catch (Exception e) {
                flag = 1;
                e.printStackTrace();
            }
        }

        return flag+"";
    }

    /**
     * 方法说明：删除
     * @author  ChenXH
     * @date  2018-12-11 13:57:58
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete (HttpServletRequest request, HttpServletResponse response){
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        //执行状态（0成功；1失败）
        int flag = 0;
        if(entityId>0){
            CarLoan carLoan = carLoanService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(carLoan)){
                //carLoan.setIsDel(0);
                try {
                    //carLoanService.updateByPrimaryKey(carLoan);
                    carLoanService.deleteByPrimaryKey(carLoan.getId());
                    //operationLog(request, "删除用户" + user.getLoginName(), TableConstants.LOG_TYPES_DEL);
                }catch (Exception e) {
                    flag = 1;
                    e.printStackTrace();
                }
            }
        }
        return flag+"";
    }


}
